﻿using housingsafety.server.Security;
using Hangfire.Annotations;
using Hangfire.Dashboard;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace housingsafety.server.Filters
{
    /// <summary>
    /// 安全验证
    /// </summary>
    [Authorize(policy: Policys.AdminOnly)]
    public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
    {
        private string policyName;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="policyName"></param>
        public HangfireAuthorizationFilter(string policyName)
        {
            this.policyName = policyName;
        }

        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool Authorize([NotNull] DashboardContext context)
        {
            var httpContext = context.GetHttpContext();
            var authService = httpContext.RequestServices.GetRequiredService<IAuthorizationService>();
            AuthorizationResult authorizationResult = authService.AuthorizeAsync(httpContext.User, this.policyName)
                .ConfigureAwait(false).GetAwaiter().GetResult();
            return authorizationResult.Succeeded;
        }
    }
}
